package org.jgs1904.rabbitmq.priority;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.jgs1904.utils.RabbitMqUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 墨苍璃
 * @date 2022年09月18日14时58分
 * <p>
 * 队列优先级 生产者
 */
public class Producer {

    private static final String QUEUE_NAME = "hello";

    public static void main(String[] args) throws Exception {
        try (Channel channel = RabbitMqUtils.getChannel()) {

            Map<String, Object> params = new HashMap(1);
            //设置队列的最大优先级 最大可以设置到 255 官网推荐 1-10 如果设置太高比较吃内存和 CPU
            params.put("x-max-priority", 100);

            //生成一个队列
            channel.queueDeclare(QUEUE_NAME, true, false, false, params);

            //给消息赋予一个 priority 属性 优先级
            AMQP.BasicProperties properties = new AMQP.BasicProperties().builder().priority(20).build();

            for (int i = 1; i < 11; i++) {
                String message = "info" + i;
                if (i == 5) {
                    System.out.println("优先消息：" + message);
                    channel.basicPublish("", QUEUE_NAME, properties, message.getBytes());
                } else {
                    AMQP.BasicProperties.Builder builder1 = new AMQP.BasicProperties.Builder();
                    builder1.priority(25);
                    channel.basicPublish("", QUEUE_NAME, builder1.build(), message.getBytes());
                }
                System.out.println("发送消息完成:" + message);
            }
        }
    }

}